package com.developerforce.chatter;
import com.sforce.soap.partner.*;
import com.sforce.soap.partner.sobject.*;
import com.sforce.ws.*;

import java.io.*;
public class ChatterMain {
	static PartnerConnection connection;
	public static void main(String[] args){
		ConnectorConfig config = new ConnectorConfig();
		config.setUsername(AuthClass.USERNAME);
		config.setPassword(AuthClass.PASSWORD);
		try {
			connection = Connector.newConnection(config);
			System.out.print("Hello " + connection.getUserInfo().getUserFullName());
			updateStatus();
			displayNewsFeed();
		} catch (ConnectionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	private static void updateStatus() throws ConnectionException, IOException {
		SObject user = new SObject();
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		print("Where are you?");
		user.setType("User");
		user.setId(connection.getUserInfo().getUserId());
		user.setField("CurrentStatus",br.readLine());
		SaveResult[] results = connection.update(new SObject[]{user});
		if (!results[0].isSuccess()){
			print("Error updating user status:" + results[0].getErrors()[0].getMessage());
		}else{
			print("Success!");
		}
		
	}
	private static void displayNewsFeed() throws ConnectionException {
		print("Querying...");
		QueryResult result = connection.query("SELECT ID, TYPE, CREATEDDATE, CREATEDBY.name, FEEDPOST.BODY FROM" +
				" NEWSFEED WHERE TYPE = 'UserStatus' ORDER BY CreatedDate  DESC, ID DESC LIMIT 10");
		int i=0;
		String[] args = new String[result.getSize()];
		for (SObject s: result.getRecords()){
			print(s.getChild("FeedPost").getField("Body").toString());
			args[i++] = s.getChild("FeedPost").getField("Body").toString();
		}
		System.out.println("The web is chattering...\n\n\n\n");
		WebSearch.search(args);
	}
	private static void print(String print){
		System.out.println(print);
	}
}
